package com.youlai.quarkus.system.common.util;

import cn.hutool.core.convert.Convert;
import com.youlai.quarkus.system.common.constant.SystemConstants;
import com.youlai.quarkus.system.security.model.SysUserDetails;
import io.quarkus.security.identity.SecurityIdentity;
import jakarta.enterprise.context.RequestScoped;
import lombok.RequiredArgsConstructor;
import org.springframework.util.PatternMatchUtils;

import java.security.Principal;
import java.util.HashSet;
import java.util.Set;

@RequiredArgsConstructor
@RequestScoped
public class SecurityIdentityContext {

    private final SecurityIdentity securityIdentity;

    /**
     * 获取当前登录人信息
     *
     * @return
     */
    public SysUserDetails getUser() {
        Principal principal = securityIdentity.getPrincipal();
        if (principal != null && principal.getClass().isAssignableFrom(SysUserDetails.class)) {
            return (SysUserDetails) principal;
        }
        return null;
    }

    /**
     * 获取用户ID
     *
     * @return
     */
    public Long getUserId() {
        Long userId = Convert.toLong(getUser().getUserId());
        return userId;
    }

    /**
     * 获取部门ID
     *
     * @return
     */
    public Long getDeptId() {
        Long userId = Convert.toLong(getUser().getDeptId());
        return userId;
    }

    /**
     * 获取数据权限范围
     *
     * @return DataScope
     */
    public Integer getDataScope() {
        Integer dataScope = Convert.toInt(getUser().getDataScope());
        return dataScope;
    }


    /**
     * 获取用户角色集合
     *
     * @return
     */
    public Set<String> getRoles() {
        return new HashSet<>(securityIdentity.getRoles());
    }

    /**
     * 获取用户权限集合
     *
     * @return
     */
    public Set<String> getPerms() {
        return null;
    }

    /**
     * 是否超级管理员
     * <p>
     * 超级管理员忽视任何权限判断
     *
     * @return
     */
    public boolean isRoot() {
        Set<String> roles = getRoles();

        if (roles.contains(SystemConstants.ROOT_ROLE_CODE)) {
            return true;
        }
        return false;
    }


    /**
     * 是否拥有权限判断
     * <p>
     * 适用业务判断(接口权限判断适用Spring Security 自带注解 PreAuthorize 判断即可 )
     *
     * @return
     */
    public boolean hasPerm(String perm) {

        if (isRoot()) {
            return true;
        }

        Set<String> perms = getPerms();

        boolean hasPerm = perms.stream().anyMatch(item -> PatternMatchUtils.simpleMatch(perm, item));
        return hasPerm;
    }

}
